new Vue({
    el: '#app',
    data: {
        oldJar: null,
        newJar: null,
        analysisResult: null,
        loading: false,
        error: null,
        selectedClass: null,
        exporting: false,
        detailsModal: null,
        uploadProgress: 0,
        maxFileSize: 100 * 1024 * 1024, // 100MB in bytes
    },
    computed: {
        canAnalyze() {
            return this.oldJar && this.newJar;
        }
    },
    created() {
        // 配置axios默认值
        axios.defaults.timeout = 300000; // 5分钟超时
        axios.defaults.maxContentLength = Infinity;
        axios.defaults.maxBodyLength = Infinity;
    },
    mounted() {
        // 等待DOM加载完成后再初始化模态框
        this.$nextTick(() => {
            const modalEl = document.getElementById('detailsModal');
            if (modalEl) {
                this.detailsModal = new bootstrap.Modal(modalEl);
            }
        });
    },
    methods: {
        handleOldJarUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            if (file.size > this.maxFileSize) {
                this.error = `文件大小不能超过100MB，当前文件大小：${(file.size / (1024 * 1024)).toFixed(2)}MB`;
                event.target.value = ''; // 清除文件选择
                return;
            }

            if (!file.name.toLowerCase().endsWith('.jar')) {
                this.error = '请选择JAR文件';
                event.target.value = '';
                return;
            }

            this.oldJar = file;
            this.error = null;
        },
        handleNewJarUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            if (file.size > this.maxFileSize) {
                this.error = `文件大小不能超过100MB，当前文件大小：${(file.size / (1024 * 1024)).toFixed(2)}MB`;
                event.target.value = ''; // 清除文件选择
                return;
            }

            if (!file.name.toLowerCase().endsWith('.jar')) {
                this.error = '请选择JAR文件';
                event.target.value = '';
                return;
            }

            this.newJar = file;
            this.error = null;
        },
        formatFileSize(bytes) {
            if (bytes === 0) return '0 字节';
            const k = 1024;
            const sizes = ['字节', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        },
        getChangeTypeText(type) {
            if (!type) return '未知';
            const types = {
                'ADDED': '新增',
                'MODIFIED': '修改',
                'DELETED': '删除'
            };
            return types[type] || type;
        },
        async analyze() {
            if (!this.oldJar || !this.newJar) {
                this.error = '请选择两个JAR文件进行比较';
                return;
            }

            const formData = new FormData();
            formData.append('oldJar', this.oldJar);
            formData.append('newJar', this.newJar);

            this.loading = true;
            this.error = null;
            this.uploadProgress = 0;

            try {
                const response = await axios.post('/api/analysis/compare', formData, {
                    timeout: 300000, // 5分钟超时
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                    onUploadProgress: (progressEvent) => {
                        this.uploadProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                    },
                    maxContentLength: Infinity,
                    maxBodyLength: Infinity
                });
                
                if (response.data.success) {
                    this.analysisResult = response.data;
                    this.error = null;
                } else {
                    this.error = response.data.error || '分析失败';
                    this.analysisResult = null;
                }
            } catch (error) {
                console.error('分析错误:', error);
                if (error.code === 'ECONNABORTED') {
                    this.error = '上传超时，请重试或减小文件大小';
                } else if (error.response) {
                    this.error = `服务器错误: ${error.response.data.message || '未知错误'}`;
                } else if (error.request) {
                    this.error = '网络错误，请检查网络连接';
                } else {
                    this.error = '上传失败，请重试';
                }
                this.analysisResult = null;
            } finally {
                this.loading = false;
            }
        },
        showDetails(classDiff) {
            this.selectedClass = classDiff;
            if (this.detailsModal) {
                this.detailsModal.show();
            } else {
                const modalEl = document.getElementById('detailsModal');
                if (modalEl) {
                    this.detailsModal = new bootstrap.Modal(modalEl);
                    this.detailsModal.show();
                }
            }
        },
        async exportExcel() {
            await this.exportFile('excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.xlsx');
        },
        async exportPdf() {
            await this.exportFile('pdf', 'application/pdf', '.pdf');
        },
        async exportFile(type, mimeType, extension) {
            if (!this.analysisResult || !this.analysisResult.success) return;
            
            this.exporting = true;
            try {
                const response = await axios.post(
                    `/api/analysis/export/${type}`,
                    this.analysisResult.result,
                    {
                        responseType: 'blob',
                        timeout: 30000 // 30秒超时
                    }
                );

                const blob = new Blob([response.data], { type: mimeType });
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                link.href = url;
                link.setAttribute('download', `jar分析报告_${timestamp}${extension}`);
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url);
            } catch (error) {
                console.error('导出错误:', error);
                if (error.response) {
                    this.error = '导出失败，请重试';
                } else if (error.request) {
                    if (error.code === 'ECONNABORTED') {
                        this.error = '导出超时，请重试';
                    } else {
                        this.error = '网络错误，请检查网络连接后重试';
                    }
                } else {
                    this.error = '系统错误，请重试';
                }
            } finally {
                this.exporting = false;
            }
        },
        clearOldJarFile() {
            this.oldJar = null;
            this.resetFileInput('oldJarFile');
            this.resetAnalysisState();
        },
        clearNewJarFile() {
            this.newJar = null;
            this.resetFileInput('newJarFile');
            this.resetAnalysisState();
        },
        clearAll() {
            this.oldJar = null;
            this.newJar = null;
            this.resetFileInput('oldJarFile');
            this.resetFileInput('newJarFile');
            this.resetAnalysisState();
        },
        resetFileInput(inputId) {
            const fileInput = document.getElementById(inputId);
            if (fileInput) {
                fileInput.value = '';
            }
        },
        resetAnalysisState() {
            this.uploadProgress = 0;
            this.analysisResult = null;
            this.error = null;
            this.selectedClass = null;
        }
    }
});
